<template>
  <div class="ek-from">
    <ekDrawer v-model="ekVisiable" :title="title" @submit="handleSubmit" :hideBtn="hideBtn" >
      <div class="ek-from-content" v-loading="loading">
        <formRender
          :form="form"
          :columns="columns"
          :disabled="disabled"
          ref="forms"
          v-if="!loading"
        />
      </div>
    </ekDrawer>
  </div>
</template>

<script setup>
import axios from "axios";
import {
  defineComponent,
  defineExpose,
  onMounted,
  getCurrentInstance,
  computed,
  watch,
  reactive,
  ref,
} from "vue";
import formRender from "@/components/form/formRender.vue";
import ekDrawer from "@/components/business/ekDrawer/index.vue";

import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElLoading } from "element-plus";
const props = defineProps({
  // 显示隐藏
  visiable: {
    type: Boolean,
    default: false,
  },
  // 表单不可编辑
  disabled: {
    type: Boolean,
    default: false,
  },
  // 是否隐藏按钮
  hideBtn: {
    type: Boolean,
    default: false,
  },
  // 标题
  title: {
    type: String,
    default: "",
  },
  // 本地布局json 文件
  formJson: {
    type: Object,
    default: () => {
      return {};
    },
  },
  // 配置
  config: {
    type: Object,
    default: () => {
      return {};
    },
  },
  // 数据id
  rowId: {
    type: [String, Number],
    default: "",
  },

});
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
const { $storage, $http, $ekLoading, $ekMessage} = globalProperties;
const store = useStore();
const router = useRouter();
const emit = defineEmits(["update:visiable",'submit']);

// 是否显示
const ekVisiable = computed({
  get() {
    return props.visiable;
  },
  set(value) {
    emit("update:visiable", value);
  },
});

/* 表单布局 */
// 表单数据
let form = ref({}); 
// 表单字段
let columns = ref([]);
//配置，todo 这些地址配置后续修改到表单配置
let config = props.config;
let modelCode = config.modelCode;
let formUrl   = config.formUrl || `/admin/basis/getFormConfig?modelCode=${modelCode}`;
let addUrl    = config.addUrl  || `/admin/basis/insert?modelCode=${modelCode}`;
let saveUrl   = config.saveUrl || `/admin/basis/update?modelCode=${modelCode}`;
let detailUrl = config.detailUrl || `/admin/basis/detail?modelCode=${modelCode}`;


async function getFormJson() {
  // 如果json直接外面传入
  if(Object.keys(props.formJson).length) {
      columns.value = props.formJson;
      props.formJson.forEach((item) => {
        form.value[item.column] = null;
    });
    return;
  }
  
  let res = await $http.post(`${formUrl}`)
  columns.value = res.data;
  res.data.forEach((item) => {
    if(item.multiple){
      form.value[item.column] = [];
    }else {
      form.value[item.column] = '';
    }
    
  });
};

// 动态表单渲染器
const forms = ref(null);
const loading = ref(false); // loading
// 表单提交
function handleSubmit(done) {
  forms.value.validate((data) => {
    const submitData = Object.fromEntries(
      // 过滤多余显示字段
      Object.entries(data).filter(([key]) => 
        !key.includes('_model_text') && !key.includes('_dim_text')
      )
    );
    $ekLoading.open();
    $http
      .post( props.rowId ? saveUrl : addUrl,
        {
          ...submitData,
      })
      .then((res) => {
        $ekMessage.success(res.message);
        emit('submit', done);
      }).finally(()=>{
        $ekLoading.close();
      });
  });
};
// 初始化表单
async function init() {
  loading.value = true;

  await getFormJson();
  // 详情或者编辑
  if (props.rowId) {
    $http
      .post(detailUrl,
        {
          id: props.rowId,
      })
      .then((res) => {
        if (res.data) {
          for (let i in res.data) {
            res.data[i] = res.data[i] + "";
          }
          form.value = res.data;
        }
        loading.value = false;
      });
  }else {
    loading.value = false;
  }
};
init();

</script>

<style scoped lang="scss">
.ek-from {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9;
  .ek-from-content {
    width: 100%;
    height: 100%;
  }
  .ek-loading {
    position: absolute;
    width: 100%;
    height: 100%;
  }
}
</style>
